package com.xuanwu.ai.flow.component;

import com.alibaba.fastjson.JSONObject;
import com.xuanwu.ai.flow._enum.ErrorCodeEnum;
import com.xuanwu.ai.flow.constant.GlobalConstant;
import com.xuanwu.ai.flow.dto.CmpDataDTO;
import com.xuanwu.ai.flow.dto.CommonContextDTO;
import com.xuanwu.ai.flow.sao.AIDetectSao;
import com.xuanwu.ai.flow.sao.req.HeapAreaDetectReq;
import com.xuanwu.ai.flow.utils.NodeDataUtils;
import com.xuanwu.ai.web.exception.BizException;
import com.yomahub.liteflow.annotation.LiteflowComponent;
import com.yomahub.liteflow.core.NodeComponent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

@LiteflowComponent(name = "地堆面积识别组件", value = "heapAreaDetectCmp")
@Slf4j
public class HeapAreaDetectCmp extends NodeComponent {
    @Autowired
    private AIDetectSao aiDetectSao;

    @Override
    public void process() throws Exception {
        CommonContextDTO customContext = this.getContextBean(CommonContextDTO.class);
        if (customContext.getToken() == null) {
            throw new BizException(ErrorCodeEnum.NO_VALID_TOKEN);
        }
        HeapAreaDetectReq heapAreaDetectReq = new HeapAreaDetectReq();
        heapAreaDetectReq.setFrontImageUrl(customContext.getFrontImageUrl());
        heapAreaDetectReq.setSideImageUrl(customContext.getSideImageUrl());
        heapAreaDetectReq.setCornerImageUrl(customContext.getCornerImageUrl());
        JSONObject jsonObject = aiDetectSao.heapAreaDetect(customContext.getToken(), heapAreaDetectReq);
        log.info("地堆面积识别结果:{}", jsonObject.getJSONObject("data"));
        // 设置节点数据
        NodeDataUtils.setStepNodeData(customContext, this.getCmpData(CmpDataDTO.class).getUuid(), this.getName(), jsonObject);

        if(jsonObject.getInteger("status").equals(GlobalConstant.CMP_EXECUTE_FAIL)){
            throw new BizException(ErrorCodeEnum.CMP_EXECUTE_FAIL, this.getName());
        }
    }
}
